package com.nulldev.util.web.HttpServer3.extensions.nCaptcha.captchas.v4.proposal_a;

import com.nulldev.util.VariableAPI.RandomUtil;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.security.hashAPI.Hashes;
import com.nulldev.util.security.hashAPI.Hashes.Hashables;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.user.User;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.util.UUIDCookieLoader;
import com.nulldev.util.web.HttpServer3.legacyPages.v1.RequestType;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;

public class POWCaptchaPage extends HttpPage3 {

	private static final int POW_COMPLEXITY = 8;
	private static final String POW_SECRET = RandomUtil.hexString(24);

	public POWCaptchaPage() {
		super("/captcha/pow", true);
		super.setCachingMethod(CachingMethod.NO_CACHE);
	}

	@Override
	public Response onRequest(final Request request) {
		final User user = UUIDCookieLoader.userFromRequest(request);
		if (user == null) {
			return new Response(403);
		}

		if (request.getType() == RequestType.GET) {
			final String KEY = (user.uuid() + POW_SECRET);
			final String KEY_SHA256 = (String) Hashes.get(Hashables.SHA256).hash(KEY.getBytes());
			user.setExpectedResults(new String[]
				{ KEY });
			final UniJsonValue obj = UniJsonValue.object();
			obj.add("challenge", KEY_SHA256);
			obj.add("complexity", POW_COMPLEXITY);
			obj.add("uuid", user.uuid());
			return new Response(200, obj, obj);
		} else if (request.getType() == RequestType.POST) {

		} else {
			return new Response(400);
		}
		return null;
	}

}
